package com.fuyun.microservice.codec;

import com.fuyun.microservice.codec.msg.Header;
import com.fuyun.microservice.codec.msg.LoginResponseMessage;
import com.fuyun.microservice.codec.msg.Message;
import com.fuyun.microservice.utils.BufferUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;

@Slf4j
@ChannelHandler.Sharable
public class LoginResponseMessageCodec extends MessageToMessageCodec<Message, LoginResponseMessage> {
    @Override
    protected void encode(ChannelHandlerContext ctx, LoginResponseMessage msg, List<Object> out) {
        ByteBuf bodyBuffer = Unpooled.buffer(36);
        bodyBuffer.writeInt(msg.getRspCode());
        bodyBuffer.writeBytes(BufferUtil.toFixedBytes(msg.getRspMessage(), 32));

        msg.setBodyBuffer(bodyBuffer.array());
        ReferenceCountUtil.release(bodyBuffer);
        out.add(msg);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, Message msg, List<Object> out) {
        Header header = msg.getHeader();
        if (header.getCommandId() != PacketType.CONNECTRSPONSE.getCommandId()) {
            //不解析，交给下一个codec
            out.add(msg);
            return;
        }

        LoginResponseMessage loginResponseMessage = new LoginResponseMessage(header.getSequenceNo());
        BeanUtils.copyProperties(msg, loginResponseMessage);
        ByteBuf bodyBuffer = Unpooled.wrappedBuffer(msg.getBodyBuffer());
        int rspCode = bodyBuffer.readInt();
        String rspMessage = bodyBuffer.readBytes(32).toString(BufferUtil.CHARSET_DEFAULT);

        loginResponseMessage.setRspCode(rspCode);
        loginResponseMessage.setRspMessage(rspMessage);
        ReferenceCountUtil.release(bodyBuffer);

        out.add(loginResponseMessage);
    }
}
